package double_pointer;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86185
 * Date: 2023-12-02
 * Time: 16:22
 */
public class ThreeNumSumClosest {
    public static int threeSumClosest(int[] nums, int target) {
        Arrays.sort(nums);
        int ans = Integer.MAX_VALUE;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length - 2; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            int aim = target - nums[i];
            while (left < right) {
                int sum = nums[left] + nums[right];
                if(sum < aim) {
                    left++;
                } else if(sum > aim) {
                    right--;
                } else {
                    ans = nums[i] + sum;
                    break;
                }
                if(Math.abs(sum - aim) < min) {
                    min = Math.abs(sum - aim);
                    ans = nums[i] + sum;
                }
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[]{1,1,-1}, 1));
    }
}
